<template>
  <div>
    <div class="box">
      <!-- 搜索 -->
      <div class="serch">
        <div class="header">
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item>
              <div class="tb_box">
                <span class="tb_text">商品名称</span>
                <input
                  class="tb_input"
                  type="text"
                  v-model="serch_position_name"
                  placeholder="请输入"
                />
              </div>
            </el-form-item>
            <el-form-item>
              <div class="tb_box">
                <span class="tb_text">&nbsp;</span>
                <el-button type="primary" class="table_btn" @click="search">
                  <el-icon> <Search /> </el-icon>
                  搜索
                </el-button>
                <el-button class="table_btn" @click="reset">
                  <el-icon> <Refresh /> </el-icon>
                  重置
                </el-button>
                <el-button
                  type="success"
                  class="table_btn"
                  @click="openAddTerritory(0)"
                >
                  <el-icon><Plus /></el-icon>
                  添加
                </el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </div>

      <!-- 表格 -->
      <div class="table">
        <el-table
          type="index"
          :data="tableData"
          :key="index"
          max-height="100%"
          style="width: 100% !important; overflow: hidden"
          stripe
          v-loading="Loading"
        >
          <el-table-column type="index" label="序号" width="60px" />
          <el-table-column prop="name" label="商品名称" />
          <el-table-column prop="price" label="价格" />
          <el-table-column prop="discounted_price" label="优惠价" />
          <el-table-column prop="detail_link" label="详细链接" />
          <el-table-column prop="image" label="商品图片">
            <template #default="{ row }">
              <img
                :src="`http://127.0.0.1:8000${row.image}`"
                alt=""
                style="width: 95%"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" class="Operation" width="200px">
            <template #default="{ row }">
              <div class="but_Settings">
                <button @click="reviseTerritory(1, row)" class="btn_Binding">
                  <span>修改</span>
                </button>
                <button @click="openDelest(row)" class="btn_delete">
                  <span>删除</span>
                </button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 编辑弹窗 -->
      <el-dialog :title="title" v-model="dialogFormVisible" width="50%">
        <el-form :model="form">
          <el-form-item label="商品名称">
            <el-input v-model="form.name" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="商品价格">
            <el-input v-model="form.price" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item label="优惠价格">
            <el-input
              v-model="form.discounted_price"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="商品详细链接">
            <el-input v-model="form.detail_link" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="图片:">
            <el-upload
              ref="upload"
              class="avatar-uploader"
              :show-file-list="false"
              :limit="1"
              :on-exceed="handleExceed"
              @change="
                (file) => {
                  handleFileChange(file);
                }
              "
            >
              <div v-if="form.image">
                <img v-if="imageUrl == null" :src="form.image" class="avatar" />
                <img v-else :src="imageUrl" class="avatar" />
              </div>

              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="reset">取 消</el-button>
          <el-button type="primary" @click="onsubmit()">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 确认弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        width="500"
        :before-close="handleClose"
        style="margin-top: 15%"
      >
        <span>{{ dialogTitle }}</span>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button
              type="primary"
              @click="dialogVisible = false"
              v-if="dialogTitle == '你确认要上传该文件吗？'"
            >
              确定
            </el-button>
            <el-button type="primary" @click="Delete" v-else> 确定 </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import "../assets/componentStyles.css";
import {
  fetchProducts,
  addProduct,
  updateProduct,
  deleteProduct,
} from "../api/product";
import { ElMessage, genFileId } from "element-plus";
import Cookies from "js-cookie";

export default {
  data() {
    return {
      Loading: false,
      tableData: [{}], // 表格数据
      serch_position_name: "", //搜索的战地名称
      originalData: null, // 筛选暂存数据
      title: "", //弹窗标题
      dialogFormVisible: false, // 编辑弹窗控制变量
      dialogVisible: false, //确认弹窗控制变量
      dialog_status: null, // 新增修改的变量

      // 弹窗表单数据
      form: {
        name: "",
        price: "",
        discounted_price: "",
        detail_link: "",
        image: null,
      },
      excelFile: null, //excel文件

      //状态选项
      dialogTitle: "", //确认弹窗文字
      deleteID: 0, //删除ID
      imageUrl: null, //图片回显路径
    };
  },

  mounted() {
    this.getList();
  },

  methods: {
    // 获取数据
    getList() {
      fetchProducts()
        .then((res) => {
          console.log(res);
          this.tableData = res;
        })
        .catch((error) => {
          console.log(error);
          ElMessage.error(error);
        });
    },

    // 新增弹窗
    openAddTerritory(id) {
      this.dialog_status = id;
      this.reset(); //重置
      this.dialogFormVisible = true;
      this.title = "新增商品";
    },

    // 修改弹框
    reviseTerritory(id, row) {
      this.form = row;
      this.dialog_status = id;
      this.dialogFormVisible = true;
      this.title = "修改商品";
    },

    // 重置
    reset() {
      this.form = {
        name: "",
        price: "",
        discounted_price: "",
        detail_link: "",
        image: "",
      };
      this.dialogFormVisible = false;
      this.getList();
    },

    // 提交表单
    onsubmit() {
      this.form.uploader = Cookies.get("user_id");
      this.form.modifier = Cookies.get("user_id");
      const params = new FormData();
      // 新增
      if (this.dialog_status == 0) {
        Object.keys(this.form).forEach((key, index) => {
          params.append(String(key), this.form[key]);
        });
        addProduct(params)
          .then((res) => {
            this.getList(this.currentPage, this.page_size);
            this.dialogFormVisible = false;
            ElMessage({
              message: "新增成功",
              type: "success",
            });
          })
          .catch((err) => {
            ElMessage({
              message: "请检查您上传的数据或稍后再试",
              type: "error",
            });
          });
      }
      // 修改
      else if (this.dialog_status == 1) {
        Object.keys(this.form).forEach((key, index) => {
          params.append(String(key), this.form[key]);
          console.log(this.form[key]);
        });
        try {
          updateProduct(this.form.id, params)
            .then((res) => {
              this.getList(this.currentPage, this.page_size);
              this.dialogFormVisible = false;
              ElMessage({
                message: "修改成功",
                type: "success",
              });
            })
            .catch((error) => {
              ElMessage({
                message: error,
                type: "error",
              });
            });
        } catch (error) {}
      }
    },

    openDelest(row) {
      this.dialogTitle = "您确定要删除" + row.name + "这条数据吗？";
      this.dialogVisible = true;
      this.deleteID = row.id;
    },

    // 删除单行数据
    Delete() {
      deleteProduct(this.deleteID)
        .then((res) => {
          this.dialogVisible = false;
          this.getList(this.currentPage, this.page_size);
          ElMessage({
            message: "成功删除" + row.position_name + "的战地数据·",
            type: "success",
          });
        })
        .catch((error) => {});
    },

    // 搜索方法
    search() {
      if (!this.originalData) {
        this.originalData = [...this.tableData];
      }
      if (this.serch_position_name == "") {
        this.tableData = this.originalData;
      } else {
        this.tableData = this.originalData.filter((item) => {
          let state = true;
          let itemValue = item.name;
          if (!itemValue.includes(this.serch_position_name)) {
            this.state = false;
            return;
          }
          return state;
        });
        this.serch_position_name = "";
      }
    },

    // // 上传文件
    // handleExceed(files) {
    //   this.$refs.upload.clearFiles();
    //   const file = files[0];
    //   file.uid = genFileId();
    //   this.$refs.upload.handleStart(file);
    // },
    handleFileChange(file) {
      console.log(file);
      this.form.image = file.raw;
      this.imageUrl = URL.createObjectURL(this.form.image);
    },
  },
};
</script>

<style lang="less" scoped>
.el-form-item {
  margin: 10px;
}

.table {
  margin-top: 40px;
}
// .el-form {
//   display: flex;
// }

.upload {
  width: 100px;
}
/deep/.el-upload-list {
  margin: 0;
}
/deep/.el-table td.el-table__cell div {
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 3;
  display: -webkit-box;
  -webkit-box-orient: vertical;
}
/deep/.btn_Modification,
.btn_delete,
.btn_Binding {
  margin: 0 10px;
}

// 图片上传
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color) !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader {
  margin-right: auto;
}
/deep/ .el-upload {
  border: 1px dashed var(--el-border-color) !important;
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
img {
  width: 100px;
  height: 100px;
}
</style>
>
